import React from 'react';
import {
	StyleSheet,
	View,
	Image,
	TouchableOpacity,
	ScrollView,
	RefreshControl,
	Text,
	Dimensions
} from 'react-native';
import NavigatorBar from '../../common/NavigationBar';
import MyCourseList from '../../component/MyCourseList'
import Loading from '../../common/Loading'
import { pageMyCollection } from '../../api/my'
import {setSpText,setHW} from '../../component/ScreenUtil';

import BackPressComponent from '../../common/BackPressComponent';

const { height,width } = Dimensions.get('window');
var cacheData = {
	total: 0,
	items: [],
	nextPage: 1
}
export default class MyCollection extends React.Component {
	constructor(props) {
		super(props);
		this.params=this.props.navigation.state.params;
		this.state = {
			loading: true,
			dataList: [],
			isRefreshing: false,
			moreData: false,
			isLoading: false
		}
		this.backPress = new BackPressComponent({ backPress: (e) => this.onBackPress(e) });
	}

	onBackPress() {
		// console.log('back', this);
		this.params && this.params.refreshPage && this.params.refreshPage();//返回上一个页面的refreshPage()
	}

	// 获取我的收藏
	componentDidMount() {
		this.backPress.componentDidMount();
		this._pageMyCollection()
	}
	_refreshMyCollection(){
		this.setState({ dataList: [], loading: true, isLoading: false, moreData: false});
		cacheData = {
			total: 0,
			items: [],
			nextPage: 1
		}
		this._pageMyCollection();
	}
	_pageMyCollection() {
		let json = {
			"PAGE": cacheData.nextPage,
			"ROWS": 10,
			"USER_ID": global.ECourseConstant.userInfo.uuid
		}
		pageMyCollection(json).then(res => {
			cacheData.items = this.state.dataList.concat(res.LIST);
			cacheData.total = res.PAGINATION.TOTAL;
			var data = [...cacheData.items]
			this.setState(
				{
					dataList: data,
					loading: false,
					isLoading: false,
					isRefreshing: false
				},
			);
		})
	}
	// 渲染按钮 返回按钮
	renderLeftButton(image) {
		return <TouchableOpacity
			style={{ padding: 8 }}
			onPress={() => {
				this.params&&this.params.refreshPage&&this.params.refreshPage();//返回上一个页面的refreshPage()
				this.props.navigation.goBack();//pop就会返回上一个页面
			}}>
			<Image style={{ width: 34, height: 34 }} source={image} />
		</TouchableOpacity>;
	}

	// 刷新首页
	_onRefresh = () => {
		cacheData = {
			items: [],
			nextPage: 1,
			total: 0
		}
		this.setState({
			dataList: [], // 推荐课程数据
			isLoading: false,
			isRefreshing: true,
			moreData: this.state.dataList.length ? true: false
		})
		this._pageMyCollection();
	}

	hasMoreList() {
		if (this.state.dataList.length == cacheData.total && cacheData.total > 0) {
			this.setState({
				moreData: false
			})
			return false
		}
		return true
	}
	// 加载更多数据
	_onScroll = (event) => {
		if (this.state.isLoading || !this.hasMoreList()) {
			return;
		}
		let y = event.nativeEvent.contentOffset.y;
		let height = event.nativeEvent.layoutMeasurement.height;
		let contentHeight = event.nativeEvent.contentSize.height;
		if (y + height >= contentHeight - 20) {
			this.setState({
				loadMore: true,
				isLoading: false
			}, () => {
				cacheData.nextPage = cacheData.nextPage + 1;
				this._pageMyCollection()
			});

		}
	}

	render() {
		return (
			<View style={styles.MyCollection}>
				<NavigatorBar
					title={'收藏的课程'}
					style={styles.navigatorBar}
					leftButton={this.renderLeftButton(require('../../assets/imgs/back.png'))}
				/>
				<ScrollView
					refreshControl={
						<RefreshControl
							refreshing={this.state.isRefreshing}
							onRefresh={this._onRefresh.bind(this)}
							tintColor="#FF8A00"
							// title="加载中..."
							titleColor="#ddd"
							colors={['#FF8A00']}
							progressBackgroundColor="#ffffff"
						/>
					}
					onScroll={this._onScroll.bind(this)}
					showsVerticalScrollIndicator={false}
					scrollEventThrottle={20}>
					{this.state.dataList.length?
					<MyCourseList 
						myCollection={true} 
						dataList={this.state.dataList} 
						ResetSearch={()=>this._refreshMyCollection()}
						{...this.props}>
					</MyCourseList>:null}
					{this.loadMore()}
					{this.loading()}
					{this.NoData()}
				</ScrollView>
			</View>
		);
	}
	// 加载loading
	loading(){
		if(this.state.loading){
			return(
				<View style={{height:height - 50}}>
						<Loading/>
				</View>
			)
		}
	}
	// 正在加载or底部
	loadMore(){
		if(this.state.dataList.length>10){
			if(!this.state.loading){
				if(this.state.moreData){
					return(
						<View style={styles.loadMore}>
							<Text style={styles.loadMoreText}>正在加载中...</Text>
						</View>
					)
				}else{
					return(
						<View style={styles.loadMore}>
							<Text style={styles.loadMoreText}>已经全部加载完毕</Text>
						</View>
					)
				}
			}
		}
	}
	componentWillUnmount() {
		cacheData = {
			total: 0,
			items: [],
			nextPage: 1
		}
		this.setState({
			dataList: [], // 推荐课程数据
			isLoading: false,
			moreData: false
		});
		this.backPress.componentWillUnmount();
	}
	// 没有数据
	NoData(){
		if(!this.state.loading&&!this.state.moreData&&!this.state.dataList.length){
			return(
				<Text style={styles.empty}>暂无数据</Text>
			)
		}
	}
}
const styles = StyleSheet.create({
	MyCollection: {
		flex: 1,
		backgroundColor: '#F7F7F9'
	},
	empty: {
        backgroundColor: '#fff',
        textAlign: 'center',
        height: height - setHW(100),
        lineHeight:setHW(400),
        color: '#666',
        fontSize:setSpText(28),
		width: width,
    },
	loadMore: {
		flexDirection: 'row',
		justifyContent: 'center',
		height: setHW(100),
		alignItems: 'center',
	},
	loadMoreText: {
		color: '#ddd',
	}
})